/*
 * Copyright 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.beermanager.activities;

import java.util.ArrayList;
import java.util.List;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import android.widget.AdapterView.AdapterContextMenuInfo;

import com.beermanager.R;
import com.beermanager.components.actionbar.ActionBarActivity;
import com.beermanager.domain.Bar;
import com.beermanager.facebook.FacebookConnection;
import com.beermanager.googleapi.place.PlaceEntry;
import com.beermanager.net.DownloadBarsTask;
import com.doffman.dragarea.DragArea;

public class MainActivity extends ActionBarActivity {
    private final static int TAKE_PHOTO_BAR_REQUEST_CODE = 11223344;

    private FacebookConnection mFacebookConnection;
	private LinearLayout mBarListLayout;
	private BarDraggable mSelectedBar;
    private Dialog mAddBarDialog;

    private Bar newBarTemp;
    private PersistenceManager persistenceManager;

    private DragArea mDragArea;
    
    private ArrayList<Bar> barList;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

        mFacebookConnection = new FacebookConnection(this);

        mBarListLayout = (LinearLayout) findViewById(R.id.bars_list);
        mDragArea = (DragArea) findViewById(R.id.drag_area);
        mAddBarDialog = createAddBarDialog();
        persistenceManager =  new PersistenceManager(this);
        
        ManDraggable manDraggable = (ManDraggable)findViewById(R.id.men_icon);
        manDraggable.setDragArea(mDragArea);

        barList = persistenceManager.getBarsList();
        
        for(Bar b : barList) {
        	BarDraggable barDraggable = new BarDraggable(this, b);
        	addBarDraggableToList(barDraggable);
        }
        
        addListenerBarNearButton();
	}
	
	private void downloadBars()
	{		
		final MainActivity _this = this; 
	
		new DownloadBarsTask()
		{
			@Override
			protected void onPostExecute(List<PlaceEntry> result) {
				
				if ( result == null )
				{
					System.out.println("Error loading google places...");
				}
				
				super.onPostExecute(result);
				
				 for(PlaceEntry place : result) {
					 	Bar b = new Bar("");
					 	b.fromGooglePlace(place);
			        	BarDraggable barDraggable = new BarDraggable( _this, b);
			        	addBarDraggableToList(barDraggable);
			     }
			}
		}.execute();
	}

    private void addListenerBarNearButton() {
		Button barsNear = (Button) findViewById(R.id.bars_near);
		barsNear.setOnClickListener( new OnClickListener()
		{
			@Override
			public void onClick(View arg0) {
				
				System.out.println("Click => ");
				
				downloadBars();
			}			
		});
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		mFacebookConnection.authorizeCallback(requestCode, resultCode, data);
        if(requestCode == TAKE_PHOTO_BAR_REQUEST_CODE){
            handleSmallCameraPhoto(data);
        }
	}

	@Override
	protected void onResume() {
		mFacebookConnection.extendAccessTokenIfNeeded(this, null);
		super.onResume();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.main, menu);

		// Calling super after populating the menu is necessary here to ensure
		// that the
		// action bar helpers have a chance to handle this event.
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		mSelectedBar = (BarDraggable)v;
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.bars_context_menu, menu);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
	    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
	    switch (item.getItemId()) {
	        case R.id.bars_context_menu_edit:
                showAddBarDialog(mSelectedBar.getBar());
	        	deleteBarDraggableFromList(mSelectedBar);
	        	barList.remove(mSelectedBar.getBar());
                
	        	persistenceManager.clearBarList();
	        	for(Bar b: barList)
	        		persistenceManager.storeBar(b);
	        	
	            return true;
	        case R.id.bars_context_menu_delete:
	        	barList.remove(mSelectedBar.getBar());
	        	deleteBarDraggableFromList(mSelectedBar);
	        	

	        	persistenceManager.clearBarList();
	        	for(Bar b: barList)
	        		persistenceManager.storeBar(b);
	        	
	            return true;
	        default:
	            return super.onContextItemSelected(item);
	    }
	    //System.out.println(item);
	    
	    //return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			Toast.makeText(this, "Tapped home", Toast.LENGTH_SHORT).show();
			break;

		case R.id.menu_refresh:
			Toast.makeText(this, "Fake refreshing...", Toast.LENGTH_SHORT)
					.show();
			getActionBarHelper().setRefreshActionItemState(true);
			getWindow().getDecorView().postDelayed(new Runnable() {
				@Override
				public void run() {
					getActionBarHelper().setRefreshActionItemState(false);
				}
			}, 1000);
			break;

		case R.id.menu_add_bar:
			Toast.makeText(this, "Tapped Add", Toast.LENGTH_SHORT).show();
            showAddBarDialog(null);
			break;
        case R.id.menu_customize_interface:
            Toast.makeText(this, "Tapped Customize", Toast.LENGTH_SHORT).show();
            break;
		}
		return super.onOptionsItemSelected(item);
	}

    private void addBarDraggableToList(BarDraggable barDraggable){
        barDraggable.setDragArea(mDragArea);

        registerForContextMenu(barDraggable);

        mBarListLayout.addView(barDraggable);
    }

    private void deleteBarDraggableFromList(BarDraggable barDraggable){
        barDraggable.removeFromDragArea();
        mBarListLayout.removeView(barDraggable);
    }

    /***********Add Bar Dialog*******/
    private Dialog createAddBarDialog(){
        Dialog addBarDialog = new Dialog(this);

        addBarDialog.setTitle(R.string.dialog_add_bar_title);
        addBarDialog.setContentView(R.layout.add_bar_layout);

        ImageButton cameraButton = (ImageButton) addBarDialog.findViewById(R.id.add_bar_picture_button);
        cameraButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                newBarTemp = addBarDialogGetData(newBarTemp);
                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(takePictureIntent,TAKE_PHOTO_BAR_REQUEST_CODE);
            }
        });

        Button addButton = (Button) addBarDialog.findViewById(R.id.add_bar_button);
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                newBarTemp = addBarDialogGetData(newBarTemp);

                addBarDraggableToList(new BarDraggable(MainActivity.this, newBarTemp));

                barList.add(newBarTemp);
                persistenceManager.storeBar(newBarTemp);
                
                mAddBarDialog.dismiss();
            }
        });

        return addBarDialog;
    }

    private void showAddBarDialog(Bar bar){
        if(bar == null) newBarTemp = new Bar("");
        else newBarTemp = bar;

        addBarDialogSetData(newBarTemp);

        mAddBarDialog.show();
    }

    private void handleSmallCameraPhoto(Intent intent) {
        if(intent != null){
            Bundle extras = intent.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            imageBitmap = Bitmap.createScaledBitmap(imageBitmap, (int)getResources().getDimension(R.dimen.bar_icon_width),
                    (int)getResources().getDimension(R.dimen.bar_icon_height), true);

            if(mAddBarDialog != null){
                if(newBarTemp!=null)newBarTemp.setPicture(imageBitmap);
                showAddBarDialog(newBarTemp);
            }
        }
    }

    private void addBarDialogSetData(Bar bar){
        EditText name = (EditText)mAddBarDialog.findViewById(R.id.add_bar_name);
        EditText address = (EditText) mAddBarDialog.findViewById(R.id.add_bar_address);
        EditText city = (EditText) mAddBarDialog.findViewById(R.id.add_bar_city);
        EditText country = (EditText) mAddBarDialog.findViewById(R.id.add_bar_country);
        ImageView imageView = (ImageView) mAddBarDialog.findViewById(R.id.add_bar_icon_image);

        name.setText(bar.getName());
        address.setText(bar.getAddress());
        city.setText(bar.getCity());
        country.setText(bar.getCountry());
        imageView.setImageBitmap(bar.getPicture());
    }

    private Bar addBarDialogGetData(Bar bar){

        EditText name = (EditText)mAddBarDialog.findViewById(R.id.add_bar_name);
        EditText address = (EditText) mAddBarDialog.findViewById(R.id.add_bar_address);
        EditText city = (EditText) mAddBarDialog.findViewById(R.id.add_bar_city);
        EditText country = (EditText) mAddBarDialog.findViewById(R.id.add_bar_country);

        bar.setName(name.getText().toString());
        bar.setAddress(address.getText().toString());
        bar.setCity(city.getText().toString());
        bar.setCountry(country.getText().toString());

        return bar;
    }

    /***********Add Bar Dialog*******/
}
